/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import BD.Proveedor;
import BD.Seccion;
import BD.Usuario;
import DigaFoil.Controlador;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableColumn;

/**
 *
 * @author ARMGARCES
 */
public class PantallaProveedores extends javax.swing.JFrame implements Pantalla{
    private boolean sesion;
    private static JTable table;
    private String imagen = java.util.ResourceBundle.getBundle("GUI/fondos").getString("fondoPpal");
    /**
     * Creates new form VentanaPpal
     */
    public PantallaProveedores() {   
        initComponents();
                
        setTitle("DIGA C.A. - DIGAFOIL - PROVEEDORES");
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Dimension screenSize = toolkit.getScreenSize();
        this.setSize(screenSize.width,screenSize.height);
        this.setPreferredSize(screenSize);
        int x = 0;
        int y = 0;
        this.setLocation(x, y);
        this.setResizable(false);
        refreshScreen();
        
        this.addComponentListener(new ComponentAdapter() {
            @Override
            public void componentHidden(ComponentEvent e) {
                salir();
                ((JFrame)(e.getComponent())).dispose();
            }
        });
        
    }
    /**
     * 
     */
    private void refreshScreen(){
        
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                while(true){
                    try {
                        List<Proveedor> list = Controlador.getInstance().getProveedores();
                        printTable(list);                        
                        Thread.sleep(5000);
                    } catch (InterruptedException ex) {
                        String mnsj  = "Error Refrescando Ventana";
                        String title = "Error de Ejecucion!";
                        JOptionPane.showMessageDialog(Gui.getInstance().getPantalla(),mnsj,title, JOptionPane.ERROR_MESSAGE);
                    }
                }
            }
        });
        t.start();
    }
    /**
     * 
     */
    @Override
    public void salir(){   
        Gui.getInstance().pantallaPpal();
        Gui.getInstance().updateSesion(); 
        this.dispose();
    }

    /**
     * 
     * @param _user 
     */
    @Override
    public void updateSesion(Usuario _user){
        if(_user != null && _user.getActivo()){
            l_sesion.setText(_user.toString());
            b_sesion.setText("Cerrar Sesion");
            sesion = false;
        }else{
            this.salir();
        }
        panelSesion.repaint();
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        fondo = new JPanelConFondo(imagen);
        panelSesion = new javax.swing.JPanel();
        b_sesion = new javax.swing.JButton();
        l_sesion = new javax.swing.JLabel();
        addProveedor = new javax.swing.JButton();
        updProveedor = new javax.swing.JButton();
        addcateg_mp = new javax.swing.JButton();
        p_tabla = new javax.swing.JPanel();

        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        fondo.setMinimumSize(new java.awt.Dimension(1024, 800));
        fondo.setPreferredSize(new java.awt.Dimension(1079, 800));

        panelSesion.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Sesion", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 10))); // NOI18N

        b_sesion.setText("Iniciar Sesion");
        b_sesion.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        b_sesion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                b_sesionActionPerformed(evt);
            }
        });

        l_sesion.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        l_sesion.setText("Usuario:  ");
        l_sesion.setMaximumSize(null);
        l_sesion.setMinimumSize(null);
        l_sesion.setPreferredSize(null);

        javax.swing.GroupLayout panelSesionLayout = new javax.swing.GroupLayout(panelSesion);
        panelSesion.setLayout(panelSesionLayout);
        panelSesionLayout.setHorizontalGroup(
            panelSesionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelSesionLayout.createSequentialGroup()
                .addGroup(panelSesionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(panelSesionLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(l_sesion, javax.swing.GroupLayout.DEFAULT_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(panelSesionLayout.createSequentialGroup()
                        .addGap(59, 59, 59)
                        .addComponent(b_sesion)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        panelSesionLayout.setVerticalGroup(
            panelSesionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelSesionLayout.createSequentialGroup()
                .addComponent(l_sesion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(b_sesion)
                .addContainerGap())
        );

        b_sesion.getAccessibleContext().setAccessibleDescription("");

        addProveedor.setText("Agregar Proveedor");
        addProveedor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addProveedorActionPerformed(evt);
            }
        });

        updProveedor.setText("Modificar Proveedor");
        updProveedor.setMaximumSize(null);
        updProveedor.setMinimumSize(null);
        updProveedor.setPreferredSize(null);
        updProveedor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                updProveedorActionPerformed(evt);
            }
        });

        addcateg_mp.setText("Agregar Categoria MP");

        p_tabla.setMaximumSize(null);
        p_tabla.setMinimumSize(null);

        javax.swing.GroupLayout p_tablaLayout = new javax.swing.GroupLayout(p_tabla);
        p_tabla.setLayout(p_tablaLayout);
        p_tablaLayout.setHorizontalGroup(
            p_tablaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 500, Short.MAX_VALUE)
        );
        p_tablaLayout.setVerticalGroup(
            p_tablaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 200, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout fondoLayout = new javax.swing.GroupLayout(fondo);
        fondo.setLayout(fondoLayout);
        fondoLayout.setHorizontalGroup(
            fondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(fondoLayout.createSequentialGroup()
                .addGroup(fondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(fondoLayout.createSequentialGroup()
                        .addGap(243, 243, 243)
                        .addGroup(fondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(p_tabla, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(fondoLayout.createSequentialGroup()
                                .addComponent(addProveedor)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(updProveedor, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(addcateg_mp)))
                        .addGap(0, 326, Short.MAX_VALUE))
                    .addGroup(fondoLayout.createSequentialGroup()
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(panelSesion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        fondoLayout.setVerticalGroup(
            fondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(fondoLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(panelSesion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(197, 197, 197)
                .addGroup(fondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(addProveedor)
                    .addComponent(updProveedor, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(addcateg_mp))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(p_tabla, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(286, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(fondo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(fondo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void b_sesionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_sesionActionPerformed
        // TODO add your handling code here:
        //
        boolean cerrarSesion = Controlador.getInstance().cerrarSesion();
    }//GEN-LAST:event_b_sesionActionPerformed

    private void addProveedorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addProveedorActionPerformed
        // TODO add your handling code here:
        //
        Usuario _user = Controlador.getInstance().getUser();
        if(_user != null && _user.getActivo()){
            Gui.getInstance().addProveedor();
        }
    }//GEN-LAST:event_addProveedorActionPerformed

    private void updProveedorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updProveedorActionPerformed
        // TODO add your handling code here:
        //
        Usuario _user = Controlador.getInstance().getUser();
        if(_user != null && _user.getActivo()){
            Gui.getInstance().addLugar();
        }

    }//GEN-LAST:event_updProveedorActionPerformed

    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addProveedor;
    private javax.swing.JButton addcateg_mp;
    private javax.swing.JButton b_sesion;
    private javax.swing.JPanel fondo;
    private javax.swing.JLabel l_sesion;
    private javax.swing.JPanel p_tabla;
    private javax.swing.JPanel panelSesion;
    private javax.swing.JButton updProveedor;
    // End of variables declaration//GEN-END:variables

    /**
     * 
     */
    @Override
    public void habilitarSecciones() {
        List<Seccion> secciones = new ArrayList<Seccion>();
        secciones = Controlador.getInstance().getUser().getFkidRol().getSeccionesHabilitadas();     
        // SECCIONES A SER HABILITADAS SEGUN EL ROL DE USUARIO
        
        for(Seccion seccion : secciones){
            //SECCION DE ADD USUARIO
            if(seccion.getNombre().equals("addUsuario")){
                this.addProveedor.setEnabled(true);
            }
        }
    }

    /**
     * 
     */
    @Override
    public void deshabilitarSecciones() {
        this.addProveedor.setEnabled(false);
    }
    /**
     * 
     * @param list 
     */
    private void printTable(List<Proveedor> list){
        String[] columnNames = {"COD",
                                "RIF",
                                "NOMBRE",
                                "CIUDAD",
                                "ESTADO"};
 
        Object[][] data = new Object[list.size()][5];
        int size = 0;
        size = list.size();
        table = null;
        
        for (int i = 0; i < size; i++) {
            //
            data[i][0] = list.get(i).getIdProveedor();
            data[i][1] = list.get(i).getRif();
            data[i][2] = list.get(i).getNombre();
            data[i][3] = list.get(i).getDireccion();
            data[i][4] = list.get(i).getFkidLugar().getNombre();                   
        }
        p_tabla.removeAll();
        
        table = new JTable(data, columnNames);
        //table.setPreferredScrollableViewportSize(new Dimension(500, 100));
  
        TableColumn column = null;
        for (int i = 0; i < table.getColumnCount(); i++) {            
            column = table.getColumnModel().getColumn(i);
            if (i == 2) {
                column.setPreferredWidth(300); //third column is bigger
            }
            if (i==1 ||i==3 || i==4 ) {
                column.setPreferredWidth(200); //third column is bigger
            }
        }
        //Create the scroll pane and add the table to it.
        p_tabla.setLayout(new BorderLayout());
        
                
        JScrollPane tableContainer = new JScrollPane(table); 
        
        table.setPreferredSize(new Dimension(900,200));
        p_tabla.setPreferredSize(new Dimension(900,200));
        tableContainer.setPreferredSize(new Dimension(900,200));
        
        p_tabla.add(tableContainer, BorderLayout.CENTER);
        this.setLocation(0,0);
        pack();        
        p_tabla.repaint();
    }
}
